package com.hd.swagger0411.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebFilter( "/*")
public class RequestFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        Enumeration<String> parameterNames = request.getParameterNames();
        if (parameterNames!=null) {
            while (parameterNames.hasMoreElements()) {
                System.out.println("请求参数：" + parameterNames.nextElement());
            }
        }else {
            System.out.println("没有请求参数");
        }

        //System.out.println("所有的请求头和请求体：");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String nextElement = headerNames.nextElement();//获取headerNames集合中的请求头
            String header2 = request.getHeader(nextElement);//通过请求头得到请求体
            System.err.println("请求头==key:" + nextElement+"\n请求体==value:" + header2);
        }
        //返回的是完整的url，包括Http协议，端口号，servlet名字和映射路径，但它不包含请求参数
        System.out.println("请求的url:"+request.getRequestURL());
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
